<?php
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_model.delivery.cdn_delivery_explain");
class delivery extends \ns_model\delivery\cdn_delivery_explain
{
    public function explain()
    {
        $fuc_name = (string)$this->get_c2_type();
        if(empty($fuc_name))
        {
            return $this->write_log_return('C2类型参数为空', NS_CDS_FAIL);
        }
        return $this->save_exec_log($this->$fuc_name());
    }
    /**
     * 主媒资注入CDN
     * @return array
     */
    private function video()
    {
        $action = $this->get_c2_info('action');
        if ($action === NS_CDS_DELETE)
        {
            return $this->video_destroy();
        }
        else
        {
            $action = "REGIST";
        }
        $arr_video_info = $this->get_video_info();
        if (empty($arr_video_info))
        {
            return $this->write_log_return("C2任务video数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        $cdn_import_id = $this->get_video_cdn_import_id();
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("主媒资C2任务生成主媒资CDN注入ID失败", NS_CDS_FAIL);
        }
        $task_type = "Series";
        //获取播控平台资源库栏目--用于获取栏目对于关系与资源类型
        $categorys = $this->get_category_info();
        if($categorys['ret'] != NS_CDS_SUCCE)
        {
            return $this->write_log_return($categorys['reason'],NS_CDS_FAIL);
        }
        $category_name = '';
        foreach ($categorys['data_info'] as $category)
        {
            if ((string)$category['id'] == (string)$arr_video_info['base_info']['nns_category_id'])
            {
                $category_name = $category['name'];
                break;
            }
        }
        //组装XML数组
        $arr_xml = array(
            'Objects' => array(
                array(
                    'ID' => $cdn_import_id,
                    'Action' => $action,
                    'Code' => $cdn_import_id,
                    'ElementType' => $task_type,
                    'Property' => array(
                        'Name' => $arr_video_info['base_info']['nns_name'],//节目名称
                        'AliasName' => $arr_video_info['base_info']['nns_alias_name'],//节目别名
                        'EnglishName' => $arr_video_info['base_info']['nns_eng_name'],//节目英文名称
                        'Compere' => '',//群众演员，多个以/分隔
                        'WriterDisplay' => $arr_video_info['base_info']['nns_director'],//导演，多个以/分隔
                        'ActorDisplay' => $arr_video_info['base_info']['nns_actor'],//演员，多个以/分隔
                        'Type' => $category_name, //节目类型，如电影、电视剧等
                        'ViewType' => $arr_video_info['base_info']['nns_view_type'],//节目类型对应标识
                        'Kind' => $arr_video_info['base_info']['nns_kind'],//影片类型标签，如动作、爱情等，多个以/分隔
                        'KeyWords' => $arr_video_info['base_info']['nns_keyword'],//影片关键字，如年代等，多个以/分隔
                        'OriginalCountry' => $arr_video_info['base_info']['nns_area'],//节目出产地
                        'ReleaseYear' => $arr_video_info['base_info']['nns_show_time'],//上映日期
                        'VolumnCount' => $arr_video_info['base_info']['nns_all_index'],
                        'Description' => $arr_video_info['base_info']['nns_summary'],
                        'ContentProvider' => $arr_video_info['base_info']['nns_cp_id'],
                        'Duration' => $arr_video_info['base_info']['nns_view_len'],
                        'Language' => $arr_video_info['base_info']['nns_language'],
                        'PlayCount' => '',
                        'Copyright' => '',
                        'LicensingWindowStart' => $arr_video_info['base_info']['nns_copyright_begin_date'],
                        'LicensingWindowEnd' => $arr_video_info['base_info']['nns_copyright_range'],
                        'ParentCategoryId' => '',
                        'ParentCategoryName' => '',
                        'OnlineIdentify' => '',
                    ),
                ),
            ),
        );
        //主媒资海报处理
        if(!empty($arr_video_info['base_info']['nns_image2'])) //小图
        {
            $img_s_id = np_guid_rand();
            $arr_xml['Objects'][] = array(
                'ID' => $img_s_id,
                'Action' => $action,
                'Code' => $img_s_id,
                'ElementType' => 'Picture',
                'Property' => array(
                    'FileURL' => $arr_video_info['base_info']['nns_image2'],//下载地址
                    'Type' => 2,//小图
                ),
            );
            $arr_xml['Mappings'][] = array(
                'ParentType' => 'Picture',
                'ParentID' => $img_s_id,
                'ParentCode' => $img_s_id,
                'ElementType' => $task_type,
                'ElementCode' => $cdn_import_id,
                'ElementID' => $cdn_import_id,
                'Action' => $action,
                'Property' => array(
                    'Type' => 2,//小图
                ),
            );
        }
        if(!empty($arr_video_info['base_info']['nns_image_v'])) //竖图
        {
            $img_v_id = np_guid_rand();
            $arr_xml['Objects'][] = array(
                'ID' => $img_v_id,
                'Action' => $action,
                'Code' => $img_v_id,
                'ElementType' => 'Picture',
                'Property' => array(
                    'FileURL' => $arr_video_info['base_info']['nns_image_v'],//下载地址
                    'Type' => 3,//小图
                ),
            );
            $arr_xml['Mappings'][] = array(
                'ParentType' => 'Picture',
                'ParentID' => $img_v_id,
                'ParentCode' => $img_v_id,
                'ElementType' => $task_type,
                'ElementCode' => $cdn_import_id,
                'ElementID' => $cdn_import_id,
                'Action' => $action,
                'Property' => array(
                    'Type' => 3,//小图
                ),
            );
        }
        if(!empty($arr_video_info['base_info']['nns_image_h'])) //横图
        {
            $img_h_id = np_guid_rand();
            $arr_xml['Objects'][] = array(
                'ID' => $img_h_id,
                'Action' => $action,
                'Code' => $img_h_id,
                'ElementType' => 'Picture',
                'Property' => array(
                    'FileURL' => $arr_video_info['base_info']['nns_image_h'],//下载地址
                    'Type' => 4,//横图
                ),
            );
            $arr_xml['Mappings'][] = array(
                'ParentType' => 'Picture',
                'ParentID' => $img_h_id,
                'ParentCode' => $img_h_id,
                'ElementType' => $task_type,
                'ElementCode' => $cdn_import_id,
                'ElementID' => $cdn_import_id,
                'Action' => $action,
                'Property' => array(
                    'Type' => 4,//横图
                ),
            );
        }
        if(!empty($arr_video_info['base_info']['nns_image_s'])) //方图
        {
            $img_id = np_guid_rand();
            $arr_xml['Objects'][] = array(
                'ID' => $img_id,
                'Action' => $action,
                'Code' => $img_id,
                'ElementType' => 'Picture',
                'Property' => array(
                    'FileURL' => $arr_video_info['base_info']['nns_image_s'],//下载地址
                    'Type' => 5,//方图
                ),
            );
            $arr_xml['Mappings'][] = array(
                'ParentType' => 'Picture',
                'ParentID' => $img_id,
                'ParentCode' => $img_id,
                'ElementType' => $task_type,
                'ElementCode' => $cdn_import_id,
                'ElementID' => $cdn_import_id,
                'Action' => $action,
                'Property' => array(
                    'Type' => 5,//方图
                ),
            );
        }
        $xml = $this->__array_make_to_xml($arr_xml);
        $params = array(
            'nns_task_type' => $task_type,//媒资类型
            'nns_action' => $action, //行为动作
            'nns_content' => $xml,//注入XML内容
            'nns_task_id' => $this->get_c2_info('id'),
            'nns_task_name' => $this->get_c2_info('name'),
        );
        return $this->execute($params);
    }

    /**
     * 主媒资删除
     */
    private function video_destroy()
    {
        $task_type = "Series";
        $action = 'DELETE';
        $cdn_import_id = $this->get_video_cdn_import_id();
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("主媒资C2任务生成主媒资CDN注入ID失败", NS_CDS_FAIL);
        }

        //组装XML数组
        $arr_xml = array(
            'Objects' => array(
                array(
                    'ID' => $cdn_import_id,
                    'Action' => $action,
                    'Code' => $cdn_import_id,
                    'ElementType' => $task_type,
                )
            )
        );
        $xml = $this->__array_make_to_xml($arr_xml);
        $params = array(
            'nns_task_type' => $task_type,//媒资类型
            'nns_action' => $action, //行为动作
            'nns_content' => $xml,//注入XML内容
            'nns_task_id' => $this->get_c2_info('id'),
            'nns_task_name' => $this->get_c2_info('name'),
        );
        return $this->execute($params);
    }
    /**
     * 分集注入CDN
     * @return array
     */
    private function index()
    {
        $action = $this->get_c2_info('action');
        if ($action === NS_CDS_DELETE)
        {
            return $this->index_destroy();
        }
        else
        {
            $action = "REGIST";
        }
        //获取主媒资注入ID
        $cdn_video_import_id = $this->get_video_cdn_import_id(NS_CDS_VIDEO);
        if (empty($cdn_video_import_id))
        {
            return $this->write_log_return("分集C2任务生成主媒资CDN注入ID失败", NS_CDS_FAIL);
        }

        $arr_index_info = $this->get_index_info();
        if (empty($arr_index_info))
        {
            return $this->write_log_return("C2任务index数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        $cdn_import_id = $this->get_video_cdn_import_id();
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("分集C2任务生成分集CDN注入ID失败", NS_CDS_FAIL);
        }
        $task_type = "Program";

        //组装XML数组
        $arr_xml = array(
            'Objects' => array(
                array(
                    'ID' => $cdn_import_id,
                    'Action' => $action,
                    'Code' => $cdn_import_id,
                    'ElementType' => $task_type,
                    'Property' => array(
                        'Name' => $arr_index_info['base_info']['nns_name'],//节目名称
                        'OriginalName' => '',//别名
                        'WatchFocus' => $arr_index_info['base_info']['nns_watch_focus'],//分集看点
                        'WriterDisplay' => $arr_index_info['base_info']['nns_director'],//导演，多个以/分隔
                        'ActorDisplay' => $arr_index_info['base_info']['nns_actor'],//演员，多个以/分隔个以/分隔
                        'KeyWords' => '',//影片关键字，如年代等，多个以/分隔
                        'OriginalCountry' => '',//节目出产地
                        'ReleaseYear' => $arr_index_info['base_info']['nns_release_time'],//上映日期
                        'Description' => $arr_index_info['base_info']['nns_summary'],
                        'Duration' => $arr_index_info['base_info']['nns_time_len'],//节目单集时长，电影单集系列可录入，以秒为单位
                        'Language' => '',//语言
                    ),
                ),
            ),
            'Mappings' => array(
                array(
                    'ParentType' => 'Series',
                    'ParentID' => $cdn_video_import_id,
                    'ParentCode' => $cdn_video_import_id,
                    'ElementType' => $task_type,
                    'ElementCode' => $cdn_import_id,
                    'ElementID' => $cdn_import_id,
                    'Action' => $action,
                    'Property' => array(
                        'Sequence' => $arr_index_info['base_info']['nns_index'],//标识Program分集数，以0开始
                    )
                )
            ),
        );
        //分集海报不要
        $xml = $this->__array_make_to_xml($arr_xml);
        $params = array(
            'nns_task_type' => $task_type,//媒资类型
            'nns_action' => $action, //行为动作
            'nns_content' => $xml,//注入XML内容
            'nns_task_id' => $this->get_c2_info('id'),
            'nns_task_name' => $this->get_c2_info('name'),
        );
        return $this->execute($params);
    }

    /**
     * 分集删除
     */
    private function index_destroy()
    {
        $task_type = "Program";
        $action = 'DELETE';
        $cdn_import_id = $this->get_video_cdn_import_id();
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("分集C2任务生成主媒资CDN注入ID失败", NS_CDS_FAIL);
        }

        //组装XML数组
        $arr_xml = array(
            'Objects' => array(
                array(
                    'ID' => $cdn_import_id,
                    'Action' => $action,
                    'Code' => $cdn_import_id,
                    'ElementType' => $task_type,
                )
            )
        );
        $xml = $this->__array_make_to_xml($arr_xml);
        $params = array(
            'nns_task_type' => $task_type,//媒资类型
            'nns_action' => $action, //行为动作
            'nns_content' => $xml,//注入XML内容
            'nns_task_id' => $this->get_c2_info('id'),
            'nns_task_name' => $this->get_c2_info('name'),
        );
        return $this->execute($params);
    }

    /**
     * 片源注入CDN
     * @return array
     */
    private function media()
    {
        $action = $this->get_c2_info('action');
        if ($action === NS_CDS_DELETE)
        {
            return $this->media_destroy();
        }
        else
        {
            $action = "REGIST";
        }
        //获取主媒资注入ID
        $cdn_index_import_id = $this->get_video_cdn_import_id(NS_CDS_INDEX);
        if (empty($cdn_index_import_id))
        {
            return $this->write_log_return("片源C2任务生成分集CDN注入ID失败", NS_CDS_FAIL);
        }

        $arr_media_info = $this->get_media_info();
        if (empty($arr_media_info))
        {
            return $this->write_log_return("C2任务media数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        $cdn_import_id = $this->get_video_cdn_import_id();
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("片源C2任务生成片源CDN注入ID失败", NS_CDS_FAIL);
        }
        $task_type = "Movie";
        switch (strtoupper($arr_media_info['base_info']['nns_mode']))
        {
            case 'LOW':
                $media_mode = 1;
                break;
            case 'STD':
                $media_mode = 2;
                break;
            case 'HD':
                $media_mode = 3;
                break;
            case 'SD':
                $media_mode = 4;
                break;
            case '4K':
                $media_mode = 5;
                break;
            default:
                $media_mode = 3;
                break;
        }
        //组装XML数组
        $arr_xml = array(
            'Objects' => array(
                array(
                    'ID' => $cdn_import_id,
                    'Action' => $action,
                    'Code' => $cdn_import_id,
                    'ElementType' => $task_type,
                    'Property' => array(
                        'Name' => $arr_media_info['base_info']['nns_name'],//片源名称
                        'Duration' => $arr_media_info['base_info']['nns_file_time_len'],//节目时长
                        'SystemLayer' => 1,//文件格式  默认为1，1 TS，2 3GP，3 flv，4 MP4，5 wmv，6 mp3
                        'Type' => 1,//媒体类型默认为1，1 正片，2 花絮/短，3 预告片，4 回看点播源
                        'FileURL' => !empty($this->get_c2_info('file_path')) ? $this->get_c2_info('file_path') : $arr_media_info['base_info']['nns_url'],//下载地址
                        'MediaMode' => $media_mode,//清晰度
                        'Resolution' => $arr_media_info['base_info']['nns_file_resolution'],//分辨率
                        'FileSize' => !empty($this->get_c2_info('file_size')) ? $this->get_c2_info('file_size') : $arr_media_info['base_info']['nns_file_size'],
                        'BitRateType' => $arr_media_info['base_info']['nns_kbps'],
                        'Tag' => '',
                        'MediaType' => '',
                        'LiveId' => '',
                        'BeginTime' => '',
                    ),
                ),
            ),
            'Mappings' => array(
                array(
                    'ParentType' => 'Program',
                    'ParentID' => $cdn_index_import_id,
                    'ParentCode' => $cdn_index_import_id,
                    'ElementType' => $task_type,
                    'ElementCode' => $cdn_import_id,
                    'ElementID' => $cdn_import_id,
                    'Action' => $action,
                )
            ),
        );
        $xml = $this->__array_make_to_xml($arr_xml);
        $params = array(
            'nns_task_type' => $task_type,//媒资类型
            'nns_action' => $action, //行为动作
            'nns_content' => $xml,//注入XML内容
            'nns_task_id' => $this->get_c2_info('id'),
            'nns_task_name' => $this->get_c2_info('name'),
        );
        return $this->execute($params);
    }

    /**
     * 片源删除
     */
    private function media_destroy()
    {
        $task_type = "Movie";
        $action = 'DELETE';
        $cdn_import_id = $this->get_video_cdn_import_id();
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("片源C2任务生成主媒资CDN注入ID失败", NS_CDS_FAIL);
        }

        //组装XML数组
        $arr_xml = array(
            'Objects' => array(
                array(
                    'ID' => $cdn_import_id,
                    'Action' => $action,
                    'Code' => $cdn_import_id,
                    'ElementType' => $task_type,
                )
            )
        );
        $xml = $this->__array_make_to_xml($arr_xml);
        $params = array(
            'nns_task_type' => $task_type,//媒资类型
            'nns_action' => $action, //行为动作
            'nns_content' => $xml,//注入XML内容
            'nns_task_id' => $this->get_c2_info('id'),
            'nns_task_name' => $this->get_c2_info('name'),
        );
        return $this->execute($params);
    }
    /**
     * XML生成
     * @param
     * $arr_data = array(
     *  'Objects' => array(
     *       array(
     *           'ID' => 'SERI2017091205971064',
     *           'Action' => 'REGIST',
     *           'Code' => 'SERI2017091205971064',
     *           'ElementType' => 'Series',
     *           'Property' => array(
     *               'Name' => 'XXXX',
     *               'AliasName' => 'VOD00000001',
     *           ),
     *       ),
     *       array(
     *           'ID' => 'PIC2017091205971064',
     *           'Action' => 'REGIST',
     *           'Code' => 'PIC2017091205971064',
     *           'ElementType' => 'Picture',
     *           'Property' => array(
     *               'FileURL' => 'http://127.0.0.1',
     *               'Type' => '4',
     *           ),
     *       ),
     *   ),
     *   'Mappings' => array(
     *       array(
     *               'ParentType' => "Picture",
     *               'ParentID'=>"PIC2017091205971064",
     *               'ParentCode'=>"PIC2017091205971064",
     *               'ElementType' => 'Series',
     *               'ElementID'=>"SERI2017091205971064",
     *               'ElementCode'=>"SERI2017091205971064",
     *               'Action'=>"REGIST",
     *           ),
     *       )
     * )
     */
    private function __array_make_to_xml($arr_data)
    {
        $obj_dom = new DOMDocument("1.0", 'utf-8');
        $adi = $obj_dom->createElement("ADI"); //创建ADI
        $adi_attr = $obj_dom->appendChild($adi);
        foreach ($arr_data as $k => $v)
        {
            $objects = $obj_dom->createElement($k);//创建Objects或者Mappings
            $objects_attr = $adi_attr->appendChild($objects);
            if(is_array($v) && !empty($v))
            {
                foreach ($v as $object_key => $object_value)
                {
                    $o_key = substr($k,0,-1);//创建Object或者Mapping
                    $object = $obj_dom->createElement($o_key);
                    $object_attr = $objects_attr->appendChild($object);
                    if(is_array($object_value) && !empty($object_value))//创建Object或者Mapping 节点值 Property
                    {
                        foreach ($object_value as $ob_key => $ob_val)
                        {
                            if($ob_key === 'Property' && !empty($ob_val) && is_array($ob_val))
                            {
                                foreach ($ob_val as $key => $value)
                                {
                                    $Property = $obj_dom->createElement('Property');
                                    $attr_key = $object_attr->appendChild($Property);
                                    $Property->setAttribute('Name',$key);
                                    $content = $obj_dom->createTextNode($value);
                                    $attr_key->appendchild($content);
                                }
                            }
                            else
                            {
                                $object->setAttribute($ob_key,$ob_val);
                            }
                        }
                    }
                    else
                    {
                        $object->setAttribute($object_key,$object_value);//创建Object或者Mapping 属性
                    }
                }
            }
        }

        return $obj_dom->saveXML();
    }
    /**
     * CDN注入统一发送器入口
     * 按项目进行自定义发送处理
     * @param $params array(
     *       'nns_task_type' =>类型,
     *       'nns_action' => 行为动作，
     *       'nns_content' => 注入XML内容,
     *       'nns_task_id' => C2任务ID,
     *       'nns_task_name' => C2任务名称,
     * );
     * @return array('ret','reason');
     */
    private function execute($params)
    {
        $cdn_code = NS_CDS_CDN_SUCCE;
        //生成CDN工单唯一ID
        $params['nns_id'] = $this->get_guid();
        $ftp_arr = parse_url($this->arr_sp_config['xml_ftp']);
        $port = !isset($ftp_arr['port']) ? '21' : $ftp_arr['port'];
        $ftp_path = !isset($ftp_arr['path']) ? '' : $ftp_arr['path'];
        $ftp_addr = "{$ftp_arr['scheme']}://{$ftp_arr['user']}:{$ftp_arr['pass']}@{$ftp_arr['host']}:{$port}";
        $task = $this->save_execute_import_content_v2($params['nns_content'], $ftp_addr, false,$ftp_path);
        if($task['ret'] != NS_CDS_SUCCE)
        {
            return $this->write_log_return($task['reason'], NS_CDS_FAIL);
        }
        $reason = 'XML生成成功';
        $params['nns_url'] = $task['data_info']['base_dir'];
        $params['nns_result'] = $cdn_code;
        $params['nns_send_time'] = date("Y-m-d H:i:s");
        $params['nns_result_fail_reason'] = '';
        $params['nns_notify_result'] = NS_CDS_CDN_NOTIFY_SUCCE;
        $params['nns_notify_fail_reason'] = $reason;
        $params['nns_notify_time'] = date('Y-m-d H:i:s');
        //生成C2日志
        $build_c2 = $this->build_c2_log($params);
        if($build_c2['ret'] != NS_CDS_SUCCE)
        {
            return $this->write_log_return($build_c2['reason'], $build_c2['ret']);
        }

        return $this->is_ok($cdn_code, $reason);
    }
}